// 2025/3/7
// https://leetcode.cn/problems/reverse-nodes-in-k-group/description/?envType=study-plan-v2&envId=top-100-liked
// k个一组翻转链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if (head == nullptr)
                return nullptr;
            ListNode *pre = nullptr, *cur = head, *next = head->next;
            while (next != nullptr) {
                cur->next = pre;
                pre = cur;
                cur = next;
                next = cur->next;
            }
            cur->next = pre;
            return cur;
        }
    
        ListNode* reverseKGroup(ListNode* head, int k) {
            ListNode phead(0, head), *pre = &phead;
            while(pre->next != nullptr)
            {
                ListNode *tail = pre->next;
                int i = 0;
                while(i < k - 1)
                {
                    if(tail->next != nullptr)
                    {
                        tail = tail->next;
                        i++;
                    }
                    else
                        break;
                }
                if(i != k - 1)
                    break;
    
                ListNode *next = tail->next;
                tail->next = nullptr;
                ListNode *newtail = pre->next;
                pre->next = reverseList(pre->next);
                newtail->next = next;
                pre = newtail;
            }
    
            return phead.next;
        }
    };